from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import RegistrationForm

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)

def auth_view(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request,user)
            request.session['userid'] = request.user.id
            return HttpResponseRedirect('/hotels/search')
        else:
            return HttpResponseRedirect('/guests/login')

def logout(request):
    auth.logout(request)
    #return render_to_response('login.html')
    return HttpResponseRedirect('/guests/login')

def register(request):
    if request.method == "POST":
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/guests/login')


    args = {}
    args.update(csrf(request))
    args['form'] = RegistrationForm()
    return render_to_response('register.html',args)